<?php

class connectController extends base
{

    private $_url;

    public function __construct()
    {
        parent::__construct('show');

        $this->_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    }

    public function dorrCallback()
    {
        $this->loadlib('renren');
        $code = $_GET['code'];
        $rr = new RenRen();
        $res = $rr->getToken($code);
        $access_token = $res['access_token'];
        $openid = $res['user']['id'];
        $userInfo = $rr->getUserInfo($access_token, $openid);
        $userInfo = $userInfo['response'];
        $nickname = $userInfo['name'];
        $header = $userInfo['avatar'][1]['url'];
        $gender = $userInfo['basicInformation']['sex'] == 'MALE' ? 1 : 0;
        $fromChannel = '';
        $birthday = $userInfo['basicInformation']['birthday'];
        $bindInfo = compact('nickname', 'header', 'gender', 'fromChannel', 'birthday');
        $expire = $res['expires_in'];
        $user_data = $this->load('social')->register($openid, $access_token, $expire, 5, 0, $bindInfo);
        $url = $this->_getUrl($user_data);
        common::go($url);
    }

    public function doCallback()
    {
        include FILE . 'lib/sina.class.php';
        if (isset($_REQUEST['code'])) {
            $o = new SaeTOAuthV2();
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = 'http://irun.hupu.com/index.php?c=connect&a=callback';
            try {
                $token = $o->getAccessToken('code', $keys);
            } catch (OAuthException $e) {
                common::pr($e->getMessage());
                exit;
            }
        }
        $access_token = $token['access_token'];
        $uid = $token['uid'];
        $c = new SaeTClientV2($access_token);
        //获取sina用户的个人信息
        $user_message = $c->show_user_by_id($uid);
        $openid = $uid;
        $expire = $token['expires_in'];
        $nickname = $user_message['name'];
        $header = $user_message['profile_image_url'];
        $gender = $user_message['gender'] == 'm' ? 1 : 0;
        $fromChannel = '';
        $bindInfo = compact('nickname', 'header', 'gender', 'fromChannel');
        $user_data = $this->load('social')->register($openid, $access_token, $expire, 3, 0, $bindInfo);
        $url = $this->_getUrl($user_data);
        common::go($url);

    }

    public function dowxCallback()
    {
        $isPub = common::request('pub') == 1;
        
        if(!$this->load('user')->getWxPubOpenId())
        {
            $this->loadLib('wx');
            $code = $_GET['code'];
            $state = $_GET['state'];
            $wx = new wx();
            $tokenInfo = $wx->getToken($code, $state);
            $token = $tokenInfo['access_token'];
            $openid = $tokenInfo['openid'];
            $expire = $tokenInfo['expires_in'];

            if($isPub)
            {
                setcookie('wxpo', $openid, time() + 86400, '/', '.hupu.com', FALSE, TRUE);
                setcookie('wxpo', $openid, time() + 86400, '/', '.ijoggers.com', FALSE, TRUE);
            }
            else
            {
                $unionid = $tokenInfo['unionid'];
                $userInfo = $wx->getUserInfo($token, $openid);
                $nickname = $userInfo['nickname'];
                $gender = $userInfo['sex'];
                $header = $userInfo['headimgurl'];
                $fromChannel = '';
                $bindInfo = compact('nickname', 'header', 'gender', 'fromChannel');
                $user_data = $this->load('social')->register($openid, $token, $expire, 4, $unionid, $bindInfo);
            }
        }

        $url = $this->_getUrl($isPub ? [] : $user_data);
        common::go($url);
    }

    public function doqqCallback()
    {
        $code = $_GET['code'];
        $state = $_GET['state'];
        include FILE . 'lib/qqConnect/QC.class.php';
        $oA = new Oauth();
        $info = $oA->qq_callback($state, $code);
        $accessToken = $info['access_token'];
        $expire = $info['expires_in'];
        $openId = $oA->get_openid($accessToken);
        $qc = new QC($accessToken, $openId);
        $arr = $qc->get_user_info();
        $nickname = $arr['nickname'];
        $header = $arr['figureurl_qq_2'];
        $fromChannel = '';
        $gender = ($arr['gender'] == '男') ? 1 : 0;
        $age = $arr['year'];
        $bindInfo = compact('nickname', 'header', 'gender', 'fromChannel', 'age');
        $user_data = $this->load('social')->register($openId, $accessToken, $expire, 2, 0, $bindInfo);
        $url = $this->_getUrl($user_data);
        common::go($url);
    }

    public function dologin()
    {
        $this->in_user();

        $rurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        if(empty($_COOKIE['rurl'])){
			setcookie('rurl',$rurl, time() + 864000, '/', '.hupu.com', FALSE, TRUE);
			setcookie('rurl',$rurl, time() + 864000, '/', '.ijoggers.com', FALSE, TRUE);
		}

        if(!empty($this->userInfo))
        {
            common::go($rurl);
            exit;
        }

        if (empty($_POST)) {
            //人人授权
            $this->loadlib('renren');
            $rr = new RenRen();
            $url = $rr->authorizeUrl();

            //新浪微博
            include FILE . 'lib/sina.class.php';
            $o = new SaeTOAuthV2();
            $code_url = $o->getAuthorizeURL('http://'.$this->config['host'].'/index.php?c=connect&a=callback');

            //qq
            include FILE . 'lib/qqConnect/QC.class.php';
            $qc = new QC();
            $qqUrl = $qc->qq_login();
            
            //微信
            $this->loadlib('wx');
            $wx = new wx();
            $wxUrl = $wx->authorizeUrl();
            
            $this->view->assign('url', $url);
            $this->view->assign('codeUrl', $code_url);
            $this->view->assign('qqUrl', $qqUrl);
            $this->view->assign('wxUrl', $wxUrl);
            $this->view->display('web_login');
        } else {
            $phone = common::request('phone', 'P');
            $pwd = common::request('pwd', 'P');
            if (empty($phone) || empty($pwd)) {
                echo "<script>alert('信息不完整！');window.history.go(-1)</script>";
                exit;
            }
            //echo $phone."=========".$pwd;
            $userInfo = $this->load('user')->getInfoByPhone($phone);
            if (empty($userInfo)) {
                echo "<script>alert('用户不存在！');window.history.go(-1)</script>";
                exit;
            }
            if ($userInfo['pwd'] != md5($pwd)) {
                echo "<script>alert('密码不正确！');window.history.go(-1)</script>";
                exit;
            }
            $time = time();
            $tokenStr = md5($userInfo['uid'] . $time . $this->config['tokenStr']);
            $uid = $this->alphaId->getHash($userInfo['uid']);
            $tokenArr = array($uid, $time, $tokenStr, md5($this->client));
            $token = implode('-', $tokenArr);
            $userInfo['token'] = $token;
            setcookie('joggers_u', $token, time() + 864000, '/', '.hupu.com', FALSE, TRUE);
            setcookie('joggers_u', $token, time() + 864000, '/', '.ijoggers.com', FALSE, TRUE);
            $url = $this->_getUrl($userInfo);
            common::go($url);
        }
    }

    private function _getUrl(array $data = [])
    {
        $pos = strpos($this->_url, 'rurl=');
        $url = $this->config['host'];
        if (isset($_COOKIE['rurl'])) {
            $url = $_COOKIE['rurl'];
            unset($_COOKIE['rurl']);
        } elseif ($pos !== false) {
            $url = urldecode(substr($this->_url, $pos + 5));
        } else{
            $url = urldecode($this->_url);
        }
        !empty($data['token']) &&setcookie('joggers_u', $data['token'], time() + 864000, '/', '.hupu.com', FALSE, TRUE);
        !empty($data['token']) &&setcookie('joggers_u', $data['token'], time() + 864000, '/', '.ijoggers.com', FALSE, TRUE);
        return $url;
    }

}
